$(document).ready(function() {
    const searchInput = $('#searchInput');
    const suggestionsDiv = $('#suggestions');
    let debounceTimer;

    // 初始化时隐藏建议框
    suggestionsDiv.hide();

    // 监听输入变化
    searchInput.on('input', function() {
        clearTimeout(debounceTimer);
        const query = $(this).val().trim();
        
        if (query.length === 0) {
            suggestionsDiv.hide();
            return;
        }

        // 使用防抖处理，300ms后才发送请求
        debounceTimer = setTimeout(() => {
            $.get('/order/api/suggestions', { query: query })
                .done(function(suggestions) {
                    if (suggestions.length > 0) {
                        const html = suggestions.map(suggestion => 
                            `<div class="suggestion-item">${suggestion}</div>`
                        ).join('');
                        suggestionsDiv.html(html).show();
                    } else {
                        suggestionsDiv.hide();
                    }
                })
                .fail(function() {
                    suggestionsDiv.hide();
                });
        }, 300);
    });

    // 点击建议项时填充搜索框
    suggestionsDiv.on('click', '.suggestion-item', function() {
        searchInput.val($(this).text());
        suggestionsDiv.hide();
    });

    // 点击页面其他地方时隐藏建议框
    $(document).on('click', function(e) {
        if (!$(e.target).closest('.search-container').length) {
            suggestionsDiv.hide();
        }
    });

    // 处理键盘上下键选择
    searchInput.on('keydown', function(e) {
        const items = suggestionsDiv.find('.suggestion-item');
        const current = suggestionsDiv.find('.suggestion-item.active');
        
        if (items.length === 0) return;

        switch(e.keyCode) {
            case 40: // 下箭头
                e.preventDefault();
                if (current.length === 0) {
                    items.first().addClass('active');
                } else {
                    current.removeClass('active');
                    current.next().addClass('active');
                }
                break;
            case 38: // 上箭头
                e.preventDefault();
                if (current.length === 0) {
                    items.last().addClass('active');
                } else {
                    current.removeClass('active');
                    current.prev().addClass('active');
                }
                break;
            case 13: // 回车键
                e.preventDefault();
                if (current.length > 0) {
                    searchInput.val(current.text());
                    suggestionsDiv.hide();
                }
                break;
        }
    });
});